const fs = require("fs-extra");
const path = require("path");

class Deploy {
	constructor() {
		let deployUrl = "E:\\Servers\\Nginx\\mgr-ui";
		let source = path.resolve(process.cwd(), "dist");
		let target = path.resolve(deployUrl + "\\html");
		let isSuccess = this.deploy(source, target);
		if (isSuccess) {
			let status = this.ngnixStatus();
			if (Number(status) < 1) {
				this.execFile("start.bat", null, deployUrl);
				return;
			}
			this.execFile("reload.bat", null, deployUrl);
		}
	}

	execFile(file, args, url) {
		return require("child_process").execFile(file, args, {cwd: url});
	}

	ngnixStatus() {
		let status = 0;
		require("child_process").exec("tasklist | findstr nginx", (error, stdout, stderr) => {
			if (!error) {
				status = stdout.indexOf("nginx.exe");
			}
		});
		return status;
	}

	deploy(source, target) {
		if (this.cleanFolder(target)) {
			return this.copy(source, target);
		}
		return false;
	}

	cleanFolder(deployPath) {
		if (fs.existsSync(deployPath) && fs.readdirSync(deployPath).length > 0) {
			fs.emptyDirSync(deployPath, (err) => {
				if (!err) {
					console.log("Folder clean success!");
					return true;
				}
				return false;
			});
		}
		return true;
	}

	copy(source, deployPath) {
		if (fs.existsSync(source) && fs.readdirSync(source).length > 0) {
			return this.copyFiles(source, deployPath);
		}
		return false;
	}

	copyFiles(filePath, deployPath) {//拷贝所有文件和文件夹
		fs.copy(filePath, deployPath, (err) => {
			if (err) {
				console.error(err);
				return false;
			}
			console.log("Project deploy successfully!");
		});
		return true;
	}
}

module.exports = Deploy;
